package com.soyorin.goods.controller;

import com.soyorin.goods.entity.Goods;
import com.soyorin.goods.service.GoodsService;
import org.springframework.http.ResponseEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService baseService;

    // 标准接口一: select-one
    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity<Goods> selectById(@PathVariable Long id) {
        Goods Goods = baseService.getById(id);
        if(Goods != null) { // return1: 成功查询到数据
            return ResponseEntity.status(200).body(Goods);
        } else { // return2: 未找到对应数据
            return ResponseEntity.status(404).body(null);
        }
    }

    // 标准接口二: select-all
    @GetMapping
    @ResponseBody
    public PageInfo<Goods> selectAll(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Goods> list = baseService.list();
        return new PageInfo<>(list);
    }

    // 标准接口三: insert
    @PostMapping
    @ResponseBody
    public ResponseEntity<Goods> insert(@RequestBody Goods Goods) {
        boolean result = baseService.save(Goods);
        if(result) { // return1: 成功插入数据
            return ResponseEntity.status(200).body(Goods);
        } else { // return2: 插入数据失败
            return ResponseEntity.status(500).body(null);
        }
    }

    // 标准接口四: delete
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResponseEntity<Goods> delete(@PathVariable Long id) {
        Goods Goods = baseService.getById(id);
        if(Goods != null) {
            boolean result = baseService.removeById(id);
            if(result) { // return1: 成功删除数据
                return ResponseEntity.status(200).body(Goods);
            } else { // return2: 删除数据失败
                return ResponseEntity.status(500).body(Goods);
            }
        } else { // return3: 未找到对应数据
            return ResponseEntity.status(404).body(null);
        }
    }

    // 标准接口五: update
    @PutMapping("/{id}")
    @ResponseBody
    public ResponseEntity<Goods> update(
            @PathVariable Long id,
            @RequestBody Goods Goods) {
        Goods.setId(id);
        boolean result = baseService.updateById(Goods);
        Goods updateGoods = baseService.getById(Goods.getId());
        if(result && updateGoods != null) { // return1: 成功更新数据
            return ResponseEntity.status(200).body(updateGoods);
        } else { // return2: 更新数据失败
            return ResponseEntity.status(500).body(Goods);
        }
    }

    // 标准接口六: select-eq
    @PostMapping("/select-eq")
    @ResponseBody
    public ResponseEntity<List<Goods>> selectEq(
            @RequestBody Map<String,Object> conditions) {
        try {
            System.out.println("🔍 [Goods] 收到查询条件: " + conditions);
            
            // 创建新的条件Map，使用正确的数据库字段名
            Map<String, Object> dbConditions = new HashMap<>();
            
            // 处理字段映射：将驼峰命名转换为下划线命名
            for (Map.Entry<String, Object> entry : conditions.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                
                // 转换字段名
                String dbField = key;
                if ("relaShopId".equals(key)) {
                    dbField = "rela_shop_id";
                } else if ("relaGoodsCategoryId".equals(key)) {
                    dbField = "rela_goods_category_id";
                } else if ("innerIndex".equals(key)) {
                    dbField = "inner_index";
                } else if ("createTime".equals(key)) {
                    dbField = "create_time";
                } else if ("updateTime".equals(key)) {
                    dbField = "update_time";
                } else if ("monthlySaleCount".equals(key)) {
                    dbField = "monthly_sale_count";
                } else if ("imageAddress".equals(key)) {
                    dbField = "image_address";
                } else if ("isOn".equals(key)) {
                    dbField = "is_on";
                }
                
                System.out.println("🔄 [Goods] 字段映射: " + key + " -> " + dbField + ", 值: " + value);
                dbConditions.put(dbField, value);
            }
            
            // 使用新的条件构建查询
            QueryWrapper<Goods> wrapper = new QueryWrapper<>();
            for (Map.Entry<String, Object> entry : dbConditions.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                
                // 对SQL关键字进行特殊处理
                if ("is_on".equals(key)) {
                    wrapper.eq("`" + key + "`", value); // 使用反引号转义
                } else {
                    wrapper.eq(key, value);
                }
            }
            
            System.out.println("🔍 [Goods] 最终SQL条件: " + wrapper.getSqlSegment());
            
            List<Goods> list = baseService.list(wrapper);
            System.out.println("✅ [Goods] 查询结果数量: " + (list != null ? list.size() : 0));
            
            if(list != null) { // return1: 成功查询到数据
                return ResponseEntity.status(200).body(list);
            } else { // return2: 未找到对应数据
                return ResponseEntity.status(404).body(null);
            }
        } catch (Exception e) {
            System.err.println("❌ [Goods] 查询过程中发生异常:");
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }
}